from nicegui import ui
import plotly.graph_objects as go

# 存储所有点的坐标
points = []


@ui.refreshable
def plot_view():
    """可刷新的折线图视图"""
    fig = go.Figure()
    if points:
        # 按添加顺序连接所有点
        x_values = [p[0] for p in points]
        y_values = [p[1] for p in points]
        fig.add_trace(go.Scatter(
            x=x_values,
            y=y_values,
            mode='lines+markers',
            line=dict(color='blue', width=2),
            marker=dict(size=12, color='red')
        ))
    fig.update_layout(
        title='折线统计图',
        xaxis_title='X 值',
        yaxis_title='Y 值',
        showlegend=False
    )
    return ui.plotly(fig)


# 创建输入框和按钮
with ui.row().classes('items-center'):
    x_input = ui.input('X').props('type=number')
    y_input = ui.input('Y').props('type=number')


    def add_point():
        """添加点"""
        try:
            x = float(x_input.value)
            y = float(y_input.value)
        except ValueError:
            ui.notify('请输入有效的数字', color='negative')
            return

        new_point = (x, y)
        if new_point not in points:
            points.append(new_point)
            plot_view.refresh()
            ui.notify(f'已添加点 ({x}, {y})', color='positive')
        else:
            ui.notify('该点已存在', color='warning')


    ui.button('添加', on_click=add_point, icon='add').props('outline')


    def remove_point():
        """删除点"""
        try:
            x = float(x_input.value)
            y = float(y_input.value)
        except ValueError:
            ui.notify('请输入有效的数字', color='negative')
            return

        try:
            points.remove((x, y))
            plot_view.refresh()
            ui.notify(f'已删除点 ({x}, {y})', color='positive')
        except ValueError:
            ui.notify('该点不存在', color='warning')


    ui.button('删除', on_click=remove_point, icon='remove').props('outline')

# 初始化图表
plot_view()

ui.run(title="动态折线图", port=8080)